const path = require("path");
const HTMLPlugin = require("html-webpack-plugin");
const webpack = require("webpack");

// 判断环境是 dev 还是 production
// 读取 package.json 里面的 NODE_ENV
const isDev = process.env.NODE_ENV === "development";

const config = {
  target: "web",
  entry: path.join(__dirname, "./src/index.js"),
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js"
  },
  // 对不同文件使用不同的 loader 进行处理
  module: {
    rules: [
      { test: /\.vue$/, loader: "vue-loader" },
      { test: /\.jsx$/, loader: "babel-loader" },
      { test: /\.css$/, use: ["style-loader", "css-loader"] },
      {
        test: /\.styl$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              sourceMap: true
            }
          },
          "stylus-loader"
        ]
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg)$/,
        loader: "url-loader",
        options: {
          publicPath: "./dist",
          limit: 10,
          name: "images/[name]-[hash:7].[ext]"
        }
      }
    ]
  },
  plugins: [
    // 使用变量区分环境
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: isDev ? '"development"' : '"production"' // 套环防报错
      }
    }),
    new HTMLPlugin()
  ]
};

if (isDev) {
  config.devtool = "#cheap-module-eval-source-map";
  config.devServer = {
    port: 8828,
    host: "0.0.0.0",
    overlay: {
      error: true
    },
    // // 把未映射地址映射到入口
    // historyFallback: {},

    // 改了组件代码，不需要整个页面重新加载
    hot: true
  };
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  );
}

module.exports = config;
